package com.alibaba.dubbo.common.interfaces.java;

import java.lang.reflect.Method;

import com.alibaba.dubbo.common.VersionSupport;
import com.alibaba.dubbo.common.interfaces.InterfaceDescriptor;
import com.alibaba.dubbo.common.interfaces.MethodDescriptor;

public class JavaInterfaceDescriptor implements InterfaceDescriptor {
	private Class<?> clazz;
	private String name;
	private MethodDescriptor[] descriptors;
	/**
	 * 
	 * @param clazz
	 */
	public JavaInterfaceDescriptor(Class<?> clazz){
		if(!clazz.isInterface()){
			throw new java.lang.IllegalArgumentException(clazz.getName() + " must be a interface");
		}
		this.clazz = clazz;
		this.name = clazz.getName();
		Method []methods = clazz.getMethods();
		descriptors = new MethodDescriptor[methods.length];
		for(int i = 0;i < methods.length;i++){
			descriptors[i] = new MethodDescriptorImpl(methods[i]);
		}
	}

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public MethodDescriptor[] getMethods() {
		return this.descriptors;
	}
	
	@Override
	public Class<?> getJavaInterface() {
		return this.clazz;
	}
	
	static class MethodDescriptorImpl implements MethodDescriptor{
		private String name;
		private Class<?> returnType;
		private Class<?> []parameterTypes;
		MethodDescriptorImpl(Method method){
			this.returnType = method.getReturnType();
			this.parameterTypes = method.getParameterTypes();
			this.name = method.getName();
		}

		@Override
		public String getName() {
			return this.name;
		}

		@Override
		public Class<?>[] getParameterTypes() {
			return this.parameterTypes;
		}

		@Override
		public Class<?> getReturnType() {
			return this.returnType;
		}
	}

	@Override
	public String getVersion() {
		return VersionSupport.getVersion(this.clazz, VersionSupport.getVersion());
	}
}
